let utils=require("../../../utils/util.js");
let tcity = require("../../../utils/cityData.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
     maskCondition:false,
     wxOpenId:"",
     wxNickName:"",
     headImgSrcType: 1,
     headImgSrc:"/imgs/icon-userhead-placeholder.png",
     wxGender:1,   
     mobile:"",
     allShopTypes: [
         {"id":1,"name":"企业"},
         { "id": 2, "name": "个人" }
       ],
     shopTypePickerIndex: 0,
     shopTypeName:"请选择店铺类型",
     provinces: [], 
     citys: [], 
     countys: [],  
     value: [0, 0, 0],
     values: [0, 0, 0],
     locationId:0,//选择的城市ID
     locationName: "请选择所在地区",
     condition: false,   
     mapLocationName:"",
     mapLocationAddress:"",
     mpaLatitude:0,
     mapLongitude:0,
     finalAddress:'',//最终的详细地址
     shopImgFullPaths:[],
     headImg:{
       FileHttpFullPath:"",
       FileRelativeFullPath:""
     },
     buttonDisable: false,
     verifyCodeTime: '发送验证码',
     isTypePlaceHolder:true ,//类型初始化样式
     isCityPlaceHolder: true  //地址初始化样式
  },
  /**
* 用户点击右上角分享
*/
  onShareAppMessage: function (res) {
    if (res.from === 'menu') {
      // 来自页面右上角转发按钮
      return {
        title: '快来上车务圈，更多人脉，更多订单！限时免费注册！',
        path: '/pages/index/index',
        imageUrl: '/imgs/share-banner.jpg'
      };
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(options.openid){
      that.setData({
        wxOpenId:options.openid
      })
    }
   
    //tcity.init(that);
    //var cityData = that.data.cityData;
    const provinces = tcity.provinceList();
    provinces.splice(0, 1);
    const citys = tcity.cityList(provinces[0].value);
    citys.splice(0, 1);
    const countys = tcity.countyList(provinces[0].value, citys[0].value);
    countys.splice(0, 1);
    // for (let i = 0; i < cityData.length; i++) {
    //   provinces.push(cityData[i]);
    // }
    // console.log('省份完成');
    // for (let i = 0; i < cityData[0].childs.length; i++) {
    //   citys.push(cityData[0].childs[i])
    // }
    // console.log('city完成');
    // for (let i = 0; i < cityData[0].childs[0].childs.length; i++) {
    //   countys.push(cityData[0].childs[0].childs[i])
    // }
    that.setData({
      'provinces': provinces,
      'citys': citys,
      'countys': countys     
    })
    console.log('初始化完成');
  }, 
  bindMobileInput:function(e){
     this.setData({
        mobile:e.detail.value
     });
  },
  bindSendCode:function(){
    var that=this;
    var mobile=that.data.mobile;
     if(mobile==''){
       wx.showToast({
         title: '请输入手机号码',
         icon:'none'
       })
       return;
     }
     var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
     if (!myreg.test(mobile)) {
       wx.showToast({
         title: '手机号有误！',
         icon: 'none'
       })
       return;
     }
     wx.request({
       url: utils.apiUrl +'/common/SendVerifyCode',
       data:{
         mobile:mobile
       },
       success:function(response){
         var data = response.data;
         if (data.status == 0){
           that.verifyCodeEvent();
           wx.showToast({
             title: '验证码发送成功',
             icon:'none'
           });
         }
       }
     });
  },
  /**
   * 获取微信头像昵称
   */
  getWxUserInfo:function(e){
    console.log(e)
    var wxUserInfo = e.detail.userInfo
    if(wxUserInfo){
      this.setData({
        wxNickName: wxUserInfo.nickName,        
        headImgSrc:wxUserInfo.avatarUrl,
        wxGender:wxUserInfo.gender,
        headImgSrcType: 1,
        "headImg.FileRelativeFullPath": wxUserInfo.avatarUrl
      })
    }    
  },
  bindShopTypePickerChange:function(e){
    var index = e.detail.value;
    var name = this.data.allShopTypes[index].name;
    this.setData({
      shopTypePickerIndex: index,
      shopTypeName: name,
      isTypePlaceHolder:false
    })
  },
  bindOpenLocationPicker: function () {
    this.setData({
      condition: true,
      maskCondition:true,
      isCityPlaceHolder:false
    })
  },
  bindLocationPickerConfirm: function () {
    var that=this;
    var val=that.data.value;
    var provinces=that.data.provinces;
    var citys=that.data.citys;
    var countys=that.data.countys;
     
     var szProvinceName=provinces[val[0]].text;
     var szCityName = citys[val[1]]!=null?citys[val[1]].text:"";
     var szCountyName = countys[val[2]]!=null?countys[val[2]].text:"";
     var szLocationName=szProvinceName+"-"+szCityName+"-"+szCountyName;
     var locationId = countys[val[2]]!=null?countys[val[2]].value:0;

    this.setData({
      condition: false,
      maskCondition: false,
      locationName:szLocationName,
      locationId:locationId
       
    });

  },
  bindLocationPickerCancel: function () {
    this.setData({
      condition: false,
      maskCondition: false,
    })
  },
  bindLocationChange: function (e) {
    //console.log(e);
    var val = e.detail.value
    var t = this.data.values;
    var cityData = this.data.cityData;

    if (val[0] != t[0]) {
      console.log('province no ');
      var s = this.data.provinces;
      const citys = tcity.cityList(s[val[0]].value);
      citys.splice(0, 1);

      const countys = tcity.countyList(s[val[0]].value, citys[0].value);
      countys.splice(0, 1);
      // const citys = [];
      // const countys = [];

      // for (let i = 0; i < cityData[val[0]].childs.length; i++) {
      //   citys.push(cityData[val[0]].childs[i])
      // }
      // if (cityData[val[0]].childs.length>0 && cityData[val[0]].childs[0].childs){
      //   for (let i = 0; i < cityData[val[0]].childs[0].childs.length; i++) {
      //     countys.push(cityData[val[0]].childs[0].childs[i])         
      //   }
      // }
      this.setData({
        citys: citys,     
        countys: countys,
        values: val,
        value: [val[0], 0, 0]       
      })
      return;
    }
    if (val[1] != t[1]) {
      console.log('city no');
      var s = this.data.provinces;
      var c = this.data.citys;
      const countys = tcity.countyList(s[val[0]].value, c[val[1]].value);
      countys.splice(0, 1);
      // const countys = [];
      // for (let i = 0; i < cityData[val[0]].childs[val[1]].childs.length; i++) {
      //   countys.push(cityData[val[0]].childs[val[1]].childs[i])
      // }
      this.setData({            
        countys: countys,
        values: val,
        value: [val[0], val[1], 0]
      })
      return;
    }
    if (val[2] != t[2]) {
      console.log('county no');
      this.setData({       
        values: val,
        value:[val[0],val[1],val[2]]
      })
      return;
    }
  },
  bindChooseLocation:function(){
    var that=this;
    wx.chooseLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var name = res.name || ''
        var address = res.address || ''
        that.setData({
          mapLocationName: name ,
          mapLocationAddress: address ,
          finalAddress:address,
          mapLatitude: latitude,
          mapLongitude: longitude
        });
      }
    });
  },
  bindChooseHeadImg: function () {
    var that = this;
    var count = 1;
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        wx.uploadFile({
          url: utils.apiUrl + '/common/upload',
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {

          },
          success: function (res) {
            var data = JSON.parse(res.data);
            data = JSON.parse(data);
            
            //do something
            that.setData({
              headImg: data,
              headImgSrc: data.FileHttpFullPath,
              headImgSrcType:2
            });
          }
        })
      }
    })
  },
  bindChooseImg:function(){
    var that=this;
    var count = 5 - this.data.shopImgFullPaths.length;
    wx.chooseImage({
      count: count, // 默认5张
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        for(let i=0;i<tempFilePaths.length;i++){
          wx.uploadFile({
            url: utils.apiUrl+'/common/upload', 
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {
              
            },
            success: function (res) {
              var data = JSON.parse(res.data);
              data=JSON.parse(data);
              var shopImgFullPaths = that.data.shopImgFullPaths;
              shopImgFullPaths.push(data);
              //do something
              that.setData({
                shopImgFullPaths: shopImgFullPaths
              });
            }
          })
        }
      },
      fail:function(e){
        wx.showToast({
          title: '上传图片失败',
          icon:'none'
        })
      }
    })
  },
  /**
  * 删除图片
  */
  catchDelImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var shopImgFullPaths = this.data.shopImgFullPaths;
    if (shopImgFullPaths.length > 0) {
      shopImgFullPaths.splice(index, 1);
      this.setData({
        shopImgFullPaths: shopImgFullPaths
      });
    }
  },
  bindMaskClick: function () {
    this.setData({
      maskCondition: false,
      condition: false     
    });
  },
  bindFormSubmit:function(e){
    var that=this;

    var formData = e.detail.value;    
    if(formData.UserName==''){
      wx.showToast({
        title: '请输入姓名',
        icon:'none'
      });
      return;
    }
    if (formData.Mobile == '') {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    if (formData.VerifyCode == '') {
      wx.showToast({
        title: '请输入验证码',
        icon: 'none'
      });
      return;
    }
    if (that.data.headImgSrc == '') {
      wx.showToast({
        title: '请上传头像',
        icon: 'none'
      });
      return;
      }
      if (formData.ShopName == '') {
        wx.showToast({
          title: '请输入店铺名称',
          icon: 'none'
        });
        return;
      }
      if (!formData.ShopType) {
        wx.showToast({
          title: '请选择店铺类型',
          icon: 'none'
        });
        return;
      }
      if(that.data.locationId==0){
        wx.showToast({
          title: '请选择地区',
          icon: 'none'
        });
        return;
      }
      if (formData.Address == '') {
        wx.showToast({
          title: '请输入店铺地址',
          icon: 'none'
        });
        return;
      }
      if (formData.Description.replace(/\s+/g, '') == '') {
        wx.showToast({
          title: '请输入公司简介',
          icon: 'none'
        });
        return;
      }
      if (that.data.shopImgFullPaths.length<2){
        wx.showToast({
          title: '请至少上传2张店铺展示图片',
          icon: 'none'
        });
        return;
      }
      //build form data
      var headImgSrc = that.data.headImg.FileRelativeFullPath;
      var shopImgs = that.data.shopImgFullPaths.map(item=>{
        return item.FileRelativeFullPath
      });
      var shopTypeId = that.data.allShopTypes[formData.ShopType].id;
      formData.ShopType=shopTypeId;
      formData.WxOpenID = that.data.wxOpenId;
      formData.HeadImgSrcType = that.data.headImgSrcType;
      formData.HeadImgSrc = headImgSrc;
      formData.Gender = that.data.wxGener || 1;
      formData.LocationId = that.data.locationId;
      formData.MapLocationName = that.data.mapLocationName;
      formData.MapLocationAddress = that.data.mapLocationAddress;
      formData.MapLatitude = that.data.mapLatitude;
      formData.MapLogitude = that.data.mapLongitude;
      formData.ShopImgs=shopImgs;
    
      wx.showLoading({
        title: '正在提交,请等待..',
      })
      wx.request({
        url: utils.apiUrl + '/shop/CreateShop',
        method: "POST",
        data: formData,
        success: function (response) {
          var data = response.data;
          if (data.status == 0) {
            var userId = data.data.ShopID;
            utils.setUserId(userId);
            wx.switchTab({
              url: '../../my/my',
            });
          }
          else {
            wx.showModal({
              title: '注册失败',
              content: data.message,
              showCancel: false,
            });
          }
        },
        complete: function () {
          wx.hideLoading();
        }
      });
      return;
  },

  bindFormReset:function(){

  },

  verifyCodeEvent: function () {
    var that = this;
    if (this.data.buttonDisable) return;

    var c = 60;
    var intervalId = setInterval(function () {
      c = c - 1;
      that.setData({
        verifyCodeTime: c + 's后重发',
        buttonDisable: true
      })
      if (c == 0) {
        clearInterval(intervalId);
        that.setData({
          verifyCodeTime: '发送验证码',
          buttonDisable: false
        })
      }
    }, 1000)
  }

})